import json
import requests
import base64
import getpass
import sys
import threading
import qrcode_terminal
import pymysql
from selenium import webdriver
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info
from pyzbar.pyzbar import decode
from PIL import Image
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.action_chains import ActionChains

switch = {
    "square" : "□",
    "star" : "☆",
    "tri" : "△"
}


debug = True
if len(sys.argv)==2 and str(sys.argv[1]) == "debug":
    debug = True
def chrome():
    chrome_options = webdriver.ChromeOptions()
    # 使用headless无界面浏览器模式
    # chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
    if not debug:
        chrome_options.add_argument('--headless')   # 增加无界面选项
    chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
    chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
    chrome_options.add_argument('--no-sandbox') #沙盒模式
    # 启动浏览器，获取网页源代码
    u = webdriver.Chrome(options=chrome_options,executable_path="c:/chromedriver")  # 地址为chromedriver.exe的地址
    return u

class User():
    def __init__(self):
        self.username = ''
        self.password = ''
        self.shool = ''

    def get_username(self):
        return self.username

    def get_password(self):
        return self.password

    def get_shool(self):
        return self.shool

    def set_username(self, value):
        self.username = value

    def set_password(self, value):
        self.password = value

    def set_shool(self, value):
        self.shool = value


class Login():
    def login(self,user,u):

        url = "https://mooc.yinghuaonline.com/user/login"
        u.get(url)
        # 等待5秒
        sleep(2)
        # 选择学校
        u.find_element_by_id('schoolId').click()
        # value=15选的是中南林业科技大学涉外学院
        school = '//select/option[@value="%s"]' % user.get_shool()
        u.find_element_by_xpath(school).click()  
        # 账号
        u.find_element_by_id('username').send_keys(user.get_username())
        # 密码
        u.find_element_by_id('password').send_keys(user.get_password())
        # 登录
        u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        sleep(2)
        
        tool = Tools()
        #登录验证码
        try:
            u.find_element_by_class_name("layui-layer-btn0").click()
            yzm = u.find_element_by_id('codeImg').get_attribute('src')
            yzm = yzm.split('?')[0]
            if debug:
                pass
                #print("登录需要验证码")
            img_path = "./static/xinxi/" + user.get_username() + ".png"
            cookie = "token="+ u.get_cookies()[0]['value']
            tool.download(yzm,cookie,img_path,u,1)
            img = Image.open(img_path)
            code = tool.base64_api(uname='gksec', pwd='water123', img=img, remark="", typeid=3)
            u.find_element_by_id('code').send_keys(code)
            u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        except Exception as e:
            if debug:
                print(e)
                print("不需要验证码")
                input()

        sleep(3)
        try:
            tool.getwximage(u,user.get_username())
        except Exception as e:
            #print(e)
            print("登陆失败")
            sys.exit(0)
        sleep(300)
        cookie = u.get_cookies()[2]['value']
        # 停2秒等加载
        sleep(2)
        #若没改密码点一下
        try:
            u.find_element_by_class_name("layui-layer-btn0")
            u.find_element_by_class_name("layui-layer-btn0").click()
        except Exception as e:
            if debug:
                print(e)
        return cookie
        #print("登录成功")

class Tools():
    def getwximage(self,u,username):
        codeImgPath = './static/xinxi/%s.jpeg' % username
        url=u.find_element_by_class_name("qrcode").get_attribute('src')
        r = requests.get(url)
        with open(codeImgPath, 'wb') as f:
                #保存
                f.write(r.content)
        #将二维码绘制在控制台
        #barcode_url = ''
        #barcodes = decode(Image.open(codeImgPath))
        #for barcode in barcodes:
        #    barcode_url = barcode.data.decode("utf-8")
        #qrcode_terminal.draw(barcode_url)

    def base64_api(self,uname,pwd,img,remark,typeid):
        img = img.convert('RGB')
        buffered = BytesIO()
        img.save(buffered, format="JPEG")
        if version_info.major >= 3:
            b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
        else:
            b64 = str(base64.b64encode(buffered.getvalue()))
        data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64, "remark":remark}
        result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
        if result['success']:
            return result["data"]["result"]
        else:
            return result["message"]
        return ""

    def download(self,url,cookie,fileName,u,flag):
        if(flag == 1):
            src = url
            header = {
                "Cookie": cookie,
            }

            r = requests.get(src, headers=header)

            with open(fileName, 'wb') as f:
                f.write(r.content)
        
        else:
            ele = u.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[1]/img')
            ele.screenshot(fileName)

    def play(self,cookie,username,u):
        # 静音
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()
        playing = True
        tool = Tools()
        while(playing):
            # 播放
            playBotton = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]')
            playBotton.click()
            sleep(5)

            try:
                try:
                    yzm = u.find_element_by_xpath('//*[@id="codeImg"]').get_attribute('src')
                    #print(yzm)
                    #yzm = "https://mooc.yinghuaonline.com/service/code/aa"
                    img_path = "./static/xinxi/" + username + ".jpg"
                    tool.download(yzm, cookie, img_path, u, 1)

                    #sleep(3)
                    img = Image.open(img_path)
                    result = tool.base64_api(uname='gksec', pwd='water123', img=img, remark="", typeid=3)
                    xpath = '//*[@id="layui-layer1"]/div[2]/div/div[2]/input[2]'
                    u.find_element_by_xpath(xpath).send_keys(result)
                    u.find_element_by_link_text("开始播放").click()
                except Exception as e:
                    if debug:
                        print(e)
                    yzm = u.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[1]/img').get_attribute('src')
                    #print(yzm)
                    #yzm = "https://mooc.yinghuaonline.com/service/code/aa"
                    pattern = ""
                    pattern += switch[u.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[2]/p/span/i[1]').get_attribute('class').split("-")[1]]
                    pattern += switch[u.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[2]/p/span/i[2]').get_attribute('class').split("-")[1]]
                    pattern += switch[u.find_element_by_xpath('/html/body/div[9]/div[2]/div/div[2]/p/span/i[3]').get_attribute('class').split("-")[1]]

                    img_path = "./static/xinxi/" + username + ".png"
                    tool.download(yzm, cookie, img_path, u, -1)
                    #sleep(3)
                    img = Image.open(img_path)
                    result = tool.base64_api(uname='gksec', pwd='water123', img=img, remark=pattern, typeid=21)
                    result_list = result.split("|")

                    for i in result_list:
                        j = i.split(",")
                        j[0] = int(j[0]) + 812
                        j[1] = int(j[1]) + 329
                        ActionChains(u).move_by_offset(j[0], j[1]).click().perform() # 鼠标左键点击， 200为x坐标， 100为y坐标
                        ActionChains(u).move_by_offset(-j[0], -j[1]).perform()
                        sleep(1)
                #number = 1
                #while 1:
                #    xpath = '//*[@id="layui-layer' + str(number) +'"]/div[2]/div/div[2]/input[2]'
                #    try:
                #        u.find_element_by_xpath(xpath).send_keys(result)
                #        break
                #    except:
                #        number += 1
                #        continue
                #sleep(10)
                sleep(2)
                #判断播放状态 //*[@id="videoContent"]/div/div[2]/div[1]
                playBotton = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]')
                if 'none' in playBotton.get_attribute('style'):
                    playing = False

            except Exception as e:
                if debug:
                    print(e)
                playing = False
                #print("无验证码")

    def state(self,username,url,cookie,u):
        flag = 0
        n1 = 0
        n2 = 0
        while 1:
            u.get(url) #返回学习记录处
            sleep(0.2)
            total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
            #print("已经学习 %s 个视频" % total_catalog.text)
            surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
            #print("尚未学习 %s 个视频" % surplus_catalog.text)
            with open("./static/xinxi/app.log", 'a') as f:
                f.write(str("%s----%s : 尚未学习 %s 个视频\n" % (datetime.now(),username,surplus_catalog.text)))
            sleep(0.5)
            try:
                #未学完
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(0.5)
                href_list1 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                u.get(href_list1[n1].get_attribute('href'))
            except:
                flag = 1
            try:
                #未学
                if flag == 1:
                    u.find_element_by_id('state').click()
                    u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
                    u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                    sleep(0.5)
                    href_list2 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                    u.get(href_list2[n2].get_attribute('href'))
            except:
                if(int(surplus_catalog.text) == 0):
                    break
            # 播放
            tool = Tools()
            tool.play(cookie,username,u)

            #print("开始时间是%s" % datetime.now())
            # 每个视频停留
            time = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]')
            time = str(time.text)
            if time[8:10] == '00' and time[11:13] == '00':
                if flag == 0:
                    n1 += 1
                else:
                    n2 += 1
            sleep(int(time[8:10]) * 60 + 60)
            #print("结束时间是%s" % datetime.now())
                
        # 退出
        #print("完成")

def mysql():
    db = pymysql.connect(host='127.0.0.1',
                     port=3306,
                     user='root',
                     password='1731249586',
                     database='wangke',
                     cursorclass=pymysql.cursors.DictCursor)
    return db

def run(username, password, text_list, school):
    db = mysql()
    cursor = db.cursor()
    u = chrome()
    sql = "select `cookie` from `user` where `username`=%s" % username
    cookie = None
    if cursor.execute(sql):
        cookie = cursor.fetchone()
        cookie = cookie['cookie']
    if cookie == None or cookie == "":
        #print('该账号还没有登录，请登录')
        user = User()
        user.set_username(username)
        user.set_password(password)
        user.set_shool(school)
        login = Login()
        cookie = login.login(user, u)
        with open("./static/xinxi/app.log", 'a') as f:
            f.write(str(username + "----cookie: " + cookie + "\n"))
        sql = "update `user` set `cookie`='%s' where `username`='%s'" % (cookie,username)
        cursor = db.cursor()
        cursor.execute(sql)
        db.commit()
    tool = Tools()
    token = {'name': 'token', 'value': cookie}
    cookied = 'token=' + cookie
    u.get('https://mooc.yinghuaonline.com/user/login')
    sleep(2)
    u.add_cookie(token)
    u.get('https://mooc.yinghuaonline.com/user/')

    course_list = u.find_elements_by_link_text("学习记录")
    course_href = []
    for href in course_list:
        course_href.append(href.get_attribute('href'))

    for i in text_list:
        print(username + " : 运行成功")
        sql = "update `user` set `state`='2' where `username`='%s'" % username
        db = mysql()
        cursor = db.cursor()
        cursor.execute(sql)
        db.commit()
        while 1:
            try:
                tool.state(username, course_href[int(i)-1], cookied, u)
                break
            except:
                sleep(60)
                continue
    sql = "update `user` set `state`='1' where `username`='%s'" % username
    db = mysql()
    cursor = db.cursor()
    cursor.execute(sql)
    db.commit()
    with open("./static/xinxi/app.log", 'a') as f:
        f.write(str("%s----%s : 跑完了\n" % (datetime.now(),username)))
    print(username + " : 跑完了")
    u.quit()
    
if __name__=='__main__':
    run('20207290','LYM1228@','1','15')